package guanqu.server;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

import com.alibaba.fastjson.JSON;

import guanqu.beans.IrrBMSystem;
import guanqu.beans.RealTimeIrrBRWaterCannal;
import manager.PersistentManager;

/**
 * 获取实时渠道水情信息
 * @author 凯
 *
 */
@Deprecated
public class GetBRWaterChannel extends HttpServlet{

	@Override
	public void init() throws ServletException {
		super.init();
	}
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		
		req.setCharacterEncoding("UTF-8");
		String statdiacode = req.getParameter("data");
		
		Download download = new Download();
		
		SessionFactory sf = PersistentManager.sharemanager().getSessionFactory();
//		Session session = sf.openSession();
		Session session = sf.getCurrentSession();
		
		Transaction tx = session.beginTransaction();
		try
		{
			// 获取实时渠道信息
			Query q1 = session.createQuery("from RealTimeIrrBRWaterCannal waterC where waterC.stadiaCode = ? order by waterC.meaTime desc");
			q1.setParameter(0, statdiacode);
			q1.setMaxResults(1);
			
			List<RealTimeIrrBRWaterCannal> cannals = q1.list();
			
			download.setCannals(cannals);
//			if (cannals != null && !cannals.isEmpty()) {
//				RealTimeIrrBRWaterCannal temp = cannals.get(0);
//			}
			
			// 获取照片实时数据
			Query q2 = session.createQuery("from IrrBMSystem irr where irr.stadiaCode=? order by irr.meaTime desc");
			q2.setParameter(0, statdiacode);
			q2.setMaxResults(1);
			List<IrrBMSystem> irrBMSystems = q2.list();
			download.setSystems(irrBMSystems);
			
			tx.commit();
			download.setStatus(DownloadInfo.SUCCESS);
		}catch(Exception e)
		{
			download.setStatus(DownloadInfo.FAILED);
			tx.rollback();
			e.printStackTrace();
		}
		finally {
//			session.close();
		}
		
		System.out.println(JSON.toJSONString(download));
		resp.setCharacterEncoding("UTF-8");
		resp.getWriter().append(JSON.toJSONString(download));
	}
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doGet(req, resp);
	}
	
	// 下行數據
	public static class Download
	{
		int status;
		List<RealTimeIrrBRWaterCannal> cannals;
		List<IrrBMSystem> systems;
		public int getStatus() {
			return status;
		}
		public void setStatus(int status) {
			this.status = status;
		}
		public List<RealTimeIrrBRWaterCannal> getCannals() {
			return cannals;
		}
		public void setCannals(List<RealTimeIrrBRWaterCannal> cannals) {
			this.cannals = cannals;
		}
		public List<IrrBMSystem> getSystems() {
			return systems;
		}
		public void setSystems(List<IrrBMSystem> systems) {
			this.systems = systems;
		}
		
		
		
	}
	
}
